﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net;

using Kortex.Common;
using Kortex.AllCommandsSpace;
using  Kortex.WallMgr.NSL;
using Kortex.Container;
using Kortex.Ident_manager;
using MRG.Controls.UI;
using Kortex.Communication_objs;
using Newtonsoft.Json;
using System.IO;
using Mono.Zeroconf;
using Kortex.WallManagerSpce.CubeManager;
using Kortex.WallManagerWallControl;
using Kortex.WallManagerControl.RecorderControler;
using Kortex.WallManagerControl.REST_Server;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Kortex.KPDabaBase;
using Kortex.WallManagerControl.FIle_Show;

namespace Kortex.WallMgr
{
    public partial class WallManager : Form
    {

        #region Variable
        Int32 mCol, mRow;
        NSLcube[,] ALLCubes = null;
        Label[,] AllIplabels = null;
        Label[,] AllCubeLocLabels = null;
        Label[,] AllMstarverLabels = null;
        string mLogFileName;
       

        LedBulb.KpLedPanel[,] AllLedPanels = null;
        LoadingCircle[,] AllloadingAniMetion = null;
        SelectionType currentSelection = SelectionType.sel_none;
        Control CurrentCubeControl = null;
        Control CurrentCutSwapControl = null;
        IdentManager identMgr = new IdentManager();
        string wallinputInfo;
        string wallModeInfo;
        
        TableLayoutPanel tlp = new TableLayoutPanel();
        Panel rootPanel = new Panel();
        int Panel_len = 800,Panel_height=600,Panel_edge=50;
        string localDir = string.Empty;
        KortexGuiMain rootGui = null;
        //CubeGui CubeGuiClnt = null;
        CubeGui cubeGui1;
        WallControlGui wallControl;
        RecoderControl RecordguiControl;
        NSLcube AssinTryCube = null;
        string mFmwVersion = string.Empty;
       
        
        Color CubeBackCol = Color.BurlyWood;
        Color WallBackCol = Color.LawnGreen;
        Color tlpBackCol = Color.Gray;
        Color helightCol = Color.FloralWhite;
        Color CutSwap = Color.Aquamarine;
        string RpcIdSpiUpdare = string.Empty;
        bool isRecording = false;
        public RestServer RestSrv = null;
        string UserType = "user";
        bool isRespWorkerRunning = true;
        Thread Rev_responce_worker = null;
        List<string> LoadedIps = new List<string>();
        string ToBeAssignIp = string.Empty;
        Dictionary<string, string> SerailVsIpMap = new Dictionary<string, string>();
        //Dictionary<string, string> GenralDB = new Dictionary<string, string>();
        string mLastInputRecord ;
        Kpdabase Db;
        FileShow kpDiagnostics;
        

        bool bSerialWise = true;


        #endregion
     

        #region COnstructor
        public WallManager()
        {
            InitializeComponent();
            AutoScroingInit();
            GlobalLedsInit();
            General_Init_from_DB();


        }

        public string wallConfigInput
        {
            get
            {
               return wallinputInfo;
            }

        }

        public string wallConfigMode
        {
            get
            {
                return wallModeInfo;
            }

        }

        private void AutoScroingInit()
        {

            this.AutoScroll = true; // For Friends who are running on a low Resolution Monitor

        }

        public void SetCubeValues(int col, int row, string ip, string Mac1, string Mac2)
        {

            AllIplabels[col, row].Text = ip;
            AllIplabels[col, row].ForeColor = Color.Red;
            ALLCubes[col, row].set_ip(ip);
            ALLCubes[col, row].mMacAddress1 = Mac1;
            ALLCubes[col, row].mMacAddress2 = Mac2;

            // ALLCubes[col, row].Connect();
            /*if (ALLCubes[col, row].isConnected)
            {
                GetActiveInput(col, row);
                GetOperationState(col, row);
            }
             * */


        }

        public void SetCubeValues(int col, int row, string ip, string Mac1, string Mac2,string SerialNumber)
        {

            AllIplabels[col, row].Text = SerialNumber;
            AllIplabels[col, row].ForeColor = Color.Red;
            ALLCubes[col, row].set_ip(ip);
            ALLCubes[col, row].mMacAddress1 = Mac1;
            ALLCubes[col, row].mMacAddress2 = Mac2;

            // ALLCubes[col, row].Connect();
            /*if (ALLCubes[col, row].isConnected)
            {
                GetActiveInput(col, row);
                GetOperationState(col, row);
            }
             * */


        }

        private void ShowMstarVersion(int col,int row,string version)
        {
            AllMstarverLabels[col, row].Text = version;
        
        }
        public WallManager(Int32 col_P, Int32 row_p, KortexGuiMain Root_gui,string input_p,string WallMode)
        {
            InitializeComponent();
            mCol = col_P;
            mRow = row_p;
            rootGui = Root_gui;
            localDir = Root_gui.localDir;
            wallinputInfo = input_p;
            wallModeInfo = WallMode;

            
            ALLCubes = new NSLcube[mCol, mRow];
            AssinTryCube = new NSLcube(0, 0, this, localDir, 1, 1); // For internal purpose
            AllIplabels = new Label[mCol, mRow];
            AllCubeLocLabels = new Label[mCol, mRow];
            AllMstarverLabels = new Label[mCol, mRow];
            AllLedPanels = new LedBulb.KpLedPanel[mCol, mRow];
            AllloadingAniMetion = new LoadingCircle[mCol, mRow];
            AddTLP(col_P, row_p);
            this.Text = this.Text + " For " + input_p + " And "+ wallConfigMode;
            AutoScroingInit();
            GlobalLedsInit();
            General_Init_from_DB();
            if (Thread_optimization_check.Checked)
            {
                isRespWorkerRunning = true;
                Rev_responce_worker = new Thread(proc_recv_responceT);
                Rev_responce_worker.Name = "Wall Resp Worker";
                Rev_responce_worker.Start();
            }
           // Rest_server_start_butt_Click(null, null);
        }


        #endregion

        #region responce 


        private void proc_recv_responceT()
        {
            
            while (isRespWorkerRunning)
            {
                for (int col = 0; col < mCol; col++)
                {
                    for (int row = 0; row < mRow; row++)
                    {
                        ALLCubes[col, row].Pro_rev_responce();

                    }
                }

                Thread.Sleep(10);
               
            }
        
        }

        private void GetUpdateResult(Cube_command_reqObj req, General_responce res, string rpcID)
        {
            int id;
            if (rpcID != null)
                req.rpcPollId = rpcID;

            if (res.result.taskStatus != null)
                if (res.result.taskStatus.ToLower() == "success")
                {
                    StopAnimetion(req.mCol, req.mRow);
                    AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.inProgress_led);
                    //ALLCubes[req.mCol, req.mRow].delete_fmw_file();
                    GetfmwVersion(req.mCol, req.mRow);
                    return;
                }
                

            if (res.result.taskStatus != null)
                if (res.result.taskStatus.ToLower() == "taskidnotfound" || res.result.taskStatus.ToLower() == "fail")
                {
                    StopAnimetion(req.mCol, req.mRow);
                    AllLedPanels[req.mCol, req.mRow].SetColor(Color.Red, WhichLed.inProgress_led);
                    //ALLCubes[req.mCol, req.mRow].delete_fmw_file();
                    return;
                }

            Thread.Sleep(2000);

            id = identMgr.getNextIdent();
            string[] parm = new string[1];
            parm[0] = req.rpcPollId;
            Cube_command_reqObj obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, req.mCol, req.mRow, commandType.cmd_fmw_update_status_get, parm, null, null);
            obj.rpcPollId = req.rpcPollId; // because now this time i will get this object as requested object
            ALLCubes[req.mCol, req.mRow].Request(obj);
                     
            

        }

        private void GetSaveAllResult(Cube_command_reqObj req, General_responce res, string rpcID)
        {
            int id;
            if (rpcID != null)
                req.rpcPollId = rpcID;

            if (res.result.taskStatus != null)
                if (res.result.taskStatus.ToLower() == "success")
                {
                    StopAnimetion(req.mCol, req.mRow);
                    AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.inProgress_led);
                    //ALLCubes[req.mCol, req.mRow].delete_fmw_file();
                    //GetfmwVersion(req.mCol, req.mRow);
                    return;
                }


            if (res.result.taskStatus != null)
                if (res.result.taskStatus.ToLower() == "taskidnotfound" || res.result.taskStatus.ToLower() == "fail")
                {
                    StopAnimetion(req.mCol, req.mRow);
                    AllLedPanels[req.mCol, req.mRow].SetColor(Color.Red, WhichLed.inProgress_led);
                    //ALLCubes[req.mCol, req.mRow].delete_fmw_file();
                    return;
                }

            Thread.Sleep(100);

            id = identMgr.getNextIdent();
            string[] parm = new string[1];
            parm[0] = req.rpcPollId;
            Cube_command_reqObj obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, req.mCol, req.mRow, commandType.cmd_SaveAll_status_get, parm, null, null);
            obj.rpcPollId = req.rpcPollId; // because now this time i will get this object as requested object
            ALLCubes[req.mCol, req.mRow].Request(obj);

        }

        private void GetDiagnostics_state(Cube_command_reqObj req, General_responce res)
        {
            int id;
            id = identMgr.getNextIdent();
            Cube_command_reqObj obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, req.mCol, req.mRow, commandType.cmd_diagnostics_state_get, null, null, null);
            ALLCubes[req.mCol, req.mRow].Request(obj);
        }


        private void GettiggerDiagnosticsResult(Cube_command_reqObj req, General_responce res, string rpcID)
        {
            int id;
            if (rpcID != null)
                req.rpcPollId = rpcID;

            if (res.result.taskStatus != null)
                if (res.result.taskStatus.ToLower() == "success")
                {
                   // StopAnimetion(req.mCol, req.mRow);
                    GetDiagnostics_state(req, res);


                    return;
                }


            if (res.result.taskStatus != null)
                if (res.result.taskStatus.ToLower() == "taskidnotfound" || res.result.taskStatus.ToLower() == "fail")
                {
                    StopAnimetion(req.mCol, req.mRow);
                    AllLedPanels[req.mCol, req.mRow].SetColor(Color.Red, WhichLed.inProgress_led);
                    return;
                }

            Thread.Sleep(100);

            id = identMgr.getNextIdent();
            string[] parm = new string[1];
            parm[0] = req.rpcPollId;
            Cube_command_reqObj obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, req.mCol, req.mRow, commandType.cmd_mo_tigger_Diagnostics_status_get, parm, null, null);
            obj.rpcPollId = req.rpcPollId; // because now this time i will get this object as requested object
            ALLCubes[req.mCol, req.mRow].Request(obj);

        }

        private void AssignIpToCUbe(int col,int row,string Ip)
        {
            
            if (!AllReadyAssigned(Ip))
            {
                if (bSerialWise)
                {
                    string[] RealIp = Ip.Split("---->".ToCharArray());
                    ALLCubes[col, row].set_ip(SerailVsIpMap[RealIp[0]]);
                    AllIplabels[col, row].Text = RealIp[0];
                }
                else
                {
                    ALLCubes[col, row].set_ip(Ip);
                    AllIplabels[col, row].Text = Ip;
                }

                
            }
            

            ToBeAssignIp = string.Empty;
        
        }
        private void AssignClickedIp(string ip)
        {
            int col, row;

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                AssignIpToCUbe(col, row, ip);

            }

        
        }
        private double CheckFmwVersion()
        {
            string value = Regex.Replace(mFmwVersion, "[A-Za-z ]", "");
            string[] parts = value.Split('.');
            double version = Convert.ToDouble(parts[0] + "." + parts[1]);
            return version;
        }

        public  void Log(string logMessage, TextWriter w)
        {
            /* w.Write("\r\nLog Entry : ");
             w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                 DateTime.Now.ToLongDateString());
             w.WriteLine("  :");
             w.WriteLine("  :{0}", logMessage);
             w.WriteLine ("-------------------------------");
             * */
            w.WriteLine("{0}", logMessage.Trim());

        }
        
        private void handle_SaveInput(Cube_command_reqObj req, General_responce res)
        {

            string json;
            if (res.result.input != null)
            {
               // LastSavedInputs[req.mCol, req.mRow] = res.result.input;
                input_record rec;
                rec = new input_record(req.mCol, req.mRow, res.result.input);
                json = JsonConvert.SerializeObject(rec);
                using (StreamWriter w = File.AppendText(mLastInputRecord))
                {
                    Log(json, w);
                }


            }
           
        
        }

        private void GetLogFile(Cube_command_reqObj req, General_responce res)
        {
            int id;
            if (res.result.count != null)
            {
                req.MsgCount = Convert.ToInt32(res.result.count);
                req.linenum = 0;
            }

            
            //GuiBoxArray gui = null;
            Cube_command_reqObj obj = null;
            id = identMgr.getNextIdent();
            //gui.Add(textBox155, textBox154, textBox153);
            if(req.linenum == 0)
             obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, req.mCol, req.mRow, commandType.cmd_mo_get_log_msg_internal, null, textBox1, null);

            if (req.linenum == 0)
            {
                obj.linenum = 1;
                ALLCubes[req.mCol, req.mRow].Request(obj);
            }
            else
            {
                req.linenum = req.linenum + 1;
                ALLCubes[req.mCol, req.mRow].Request(req);
            }
            
            
            //mProducer.GetRpcStatus(obj, "Get Log Message");
        }


        private void GetDiagnosticFile(Cube_command_reqObj req, General_responce res)
        {
            int id;
            
            if (res.result.count != null)
            {
                req.MsgCount = Convert.ToInt32(res.result.count);
                req.linenum = 0;
            }


            //GuiBoxArray gui = null;
            Cube_command_reqObj obj = null;
            string[] param;
           // for (int i = 0; i < Convert.ToInt32(res.result.count); i++)
            

                if (req.linenum == 0)
                {
                    param = new string[1];
                    param[0] = "1";
                    obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, 1, req.mCol, req.mRow, commandType.cmd_mo_Get_Diagnostics_msgs_get, param, textBox1, null);
                    obj.linenum = 1;
                    
                    ALLCubes[req.mCol, req.mRow].Request(obj);
                }
                else
                {
                    req.linenum = req.linenum + 1;
                    req.args[0] = req.linenum.ToString();
                    ALLCubes[req.mCol, req.mRow].Request(req);
                }


            //mProducer.GetRpcStatus(obj, "Get Log Message");
        }

        /*
        private void GetDiagnosticFile(Cube_command_reqObj req, General_responce res)
        {
            int id;
            int count=0;
            if (res.result.count != null)
            {
                req.MsgCount = Convert.ToInt32(res.result.count);
                req.linenum = 0;
            }


            //GuiBoxArray gui = null;
            Cube_command_reqObj obj = null;
            string[] param;
            for (int i = 0; i < Convert.ToInt32(res.result.count); i++)
            {
                param = new string[1];
                param[0] = i.ToString();
                id = identMgr.getNextIdent();
                obj = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, req.mCol, req.mRow, commandType.cmd_mo_Get_Diagnostics_msgs_get, param, textBox1, null);
                ALLCubes[req.mCol, req.mRow].Request(obj);
 
            
            }

            return;
            //gui.Add(textBox155, textBox154, textBox153);
            if (req.linenum == 0)
                

            if (req.linenum == 0)
            {
                obj.linenum = 1;
                ALLCubes[req.mCol, req.mRow].Request(obj);
            }
            else
            {
                req.linenum = req.linenum + 1;
                ALLCubes[req.mCol, req.mRow].Request(req);
            }


            //mProducer.GetRpcStatus(obj, "Get Log Message");
        }
        */
        private void Diagnostic_show_butt_Click(object sender, EventArgs e)
        {

            kpDiagnostics.Show();

        }

        delegate void Func<T>(T t);


        private void displayDiagnostics(string message)
        {
            if (InvokeRequired)
            {
                Func<string> del = displayDiagnostics;
                Invoke(del, message);
                return;
            }
            //errorDisplay.Show(message);
            kpDiagnostics.Show();

            try
            {
                Monitor.Exit(AllMstarverLabels);
            }
            catch (Exception e)
            { 
            
            }
        }
       
        private void handle_result(Cube_command_reqObj req, General_responce res)
        {
            switch (req.cmdType)
            {
                case commandType.cmd_cs_gaam_upload_status_get:
                    
                        if (res.result.status != null)
                        {
                            AllLedPanels[req.mCol, req.mRow].SetToolTipTitle(res.result.status, WhichLed.gamma_led);
                            if (res.result.status == "yes")
                                AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.gamma_led);
                            else
                                AllLedPanels[req.mCol, req.mRow].SetColor(Color.Red, WhichLed.gamma_led);

                        }
                    

                    break;

                case commandType.cmd_fmw_mstar_version_get:
                    if (res.result.@string != null)
                        AllMstarverLabels[req.mCol, req.mRow].Text = res.result.@string;
                    break;
                case commandType.cmd_cube_Blink_identify_assign_mode:
                    //ToBeAssignIp = req.args[0];
                    MessageBox.Show("Please click the Cube position to Assign " + ToBeAssignIp + "At Wall Overview Area");
                    AssinTryCube.Disconnect();
                    break;
                case commandType.cmd_fmw_update_spi:
                case commandType.cmd_fmw_update_status_get:
                case commandType.cmd_fmw_update_mstar:
                case commandType.cmd_fmw_update_ps171:

                    GetUpdateResult(req, res, res.result.taskId);

                    break;
                case commandType.cmd_mo_get_log_msg_internal:
                    if (res.result.message != null)
                    {
                        
                        GetLogFile(req, res);
                        using (StreamWriter w = File.AppendText(mLogFileName + "\\" + req.mIp + "_" +req.mSerialNum + "_LogFile.txt"))
                        {
                            Log((req.mCol + "," + req.mRow+ "  " + DateTime.Now.ToString()+ "  " +  res.result.message), w);
                        }

                        
                        //MO_LogMessages_richBox.AppendText(req.mIp + " " + req.mSerialNum + " " + res.result.message);
                    }
                    else
                        StopAnimetion(req.mCol, req.mRow);

                    break;
                case commandType.cmd_mo_tigger_Diagnostics_status_get:
                case commandType.cmd_mo_tigger_Diagnostics:
                    //Delay(200);

                    GettiggerDiagnosticsResult(req, res, res.result.taskId);

                    break;

                case commandType.cmd_mo_Get_Diagnostics_msgs_get:
                    if (res.result.message != null)
                    {

                        GetDiagnosticFile(req, res);
                        using (StreamWriter w = File.AppendText(localDir + "\\" + req.mIp + "_" + req.mSerialNum + "_DiaGnosticsFile.txt"))
                        {
                            Log((req.mCol + "," + req.mRow + "  " + DateTime.Now.ToString() + "  " + res.result.message), w);
                        }
                        
                    }
                    else
                    {
                        
                        StopAnimetion(req.mCol, req.mRow);

                        
                        Monitor.Enter(AllMstarverLabels);
                        kpDiagnostics = new FileShow("Diagnostics Result For " + req.mIp, localDir + "\\" + req.mIp + "_" + req.mSerialNum + "_DiaGnosticsFile.txt");
                        //Diagnostic_show_butt.PerformClick();
                        
                        displayDiagnostics("sdsd");
                        
                        //Show GUi
                    }
                    break;
                case commandType.cmd_mo_Get_Diagnostics_count_get:

                    if (res.result.count != null)
                    {
                        FileInfo Myfile = new System.IO.FileInfo(localDir + "\\" + req.mIp + "_" + req.mSerialNum + "_DiaGnosticsFile.txt");
                        if (Myfile.Exists)
                        {
                            Myfile.Delete();
                        
                        }
                     

                        GetDiagnosticFile(req, res);
                        
                    }
                    else
                        StopAnimetion(req.mCol, req.mRow);
                    
                    break;
                case commandType.cmd_diagnostics_state_get:
                    StopAnimetion(req.mCol, req.mRow);
                    if(res.result.result == "fail")
                        AllLedPanels[req.mCol, req.mRow].SetColor(Color.Red, WhichLed.system_lealth_led);
                     else
                    AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.system_lealth_led);


                    AllLedPanels[req.mCol, req.mRow].SetToolTipTitle(res.result.result, WhichLed.system_lealth_led);

                    break;

                case commandType.cmd_dataBase_saveAll:
                case commandType.cmd_SaveAll_status_get:

                    GetSaveAllResult(req, res,res.result.taskId);

                    break;

                case commandType.cmd_mo_get_log_msg_count_internal:
                    //Delay(100);
                    if (res.result.count != null)
                        GetLogFile(req, res);
                    else
                    {
                        using (StreamWriter w = File.AppendText(mLogFileName + "\\" + req.mIp + "_" + req.mSerialNum + "_LogFile.txt"))
                        {
                            Log((req.mCol + "," + req.mRow + "  " + DateTime.Now.ToString() + "  " + "No Log Found"), w);
                        }
                        StopAnimetion(req.mCol, req.mRow);
                        AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.inProgress_led);
                    }


                    break;
                case commandType.cmd_cs_gobal_error_info_get_internal:
                    if (res.result.spectralCalibMissing != null)
                    {
                       // MessageBox.Show(res.result.spectralCalibMissing);

                        if (res.result.spectralCalibMissing.Contains("false"))
                            AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.Calib_led);
                        else
                            AllLedPanels[req.mCol, req.mRow].SetColor(Color.Red, WhichLed.Calib_led);


                        AllLedPanels[req.mCol, req.mRow].SetToolTipTitle(res.result.spectralCalibMissing, WhichLed.Calib_led);
                    }

                    break;
                case commandType.cmd_mrc_spi_module_version_get:
                    if (res.result.version != null)
                    {
                         mFmwVersion = res.result.version;
                        
                        AllCubeLocLabels[req.mCol, req.mRow].Text = (req.mRow + 1) + "," + (req.mCol+ 1) + "     FMW " + res.result.version;

                        if(CheckFmwVersion()>= 1.0)
                        {
                            GetOperationState(req.mCol, req.mRow);
                            GetActiveInput(req.mCol, req.mRow);
                            GetSpecCalibHelth(req.mCol, req.mRow);
                            GetMstar_fmw_version(req.mCol, req.mRow);
                            GetGaamStatus(req.mCol, req.mRow);
                        }

                    }
                    break;

                case commandType.cmd_gen_operation_state_get:
                    if (res.result.operation != null)
                    {
                        if (res.result.operation == "on")
                        AllLedPanels[req.mCol,req.mRow].SetColor(Color.GreenYellow, WhichLed.op_state_led);
                        else
                            AllLedPanels[req.mCol, req.mRow].SetColor(Color.Gray, WhichLed.op_state_led);

                        //AllLedPanels[req.mCol, req.mRow].StartBlink(500, 1);
                        AllLedPanels[req.mCol, req.mRow].SetToolTipTitle(res.result.operation, WhichLed.op_state_led);
                    }

                    break;
                case commandType.cmd_get_input_selected_internal:
                    handle_SaveInput(req, res);
                    break;
                case commandType.cmd_get_input_selected:
                case commandType.cmd_get_Active_input:
                    
                    if (res.result.input != null)
                    {
                        //AllLedPanels[req.mCol, req.mRow].SetColor(Color.GreenYellow, WhichLed.activeInput_led);
                        //AllLedPanels[req.mCol, req.mRow].StartBlink(500, 1);
                        AllLedPanels[req.mCol, req.mRow].SetToolTipTitle(res.result.input, WhichLed.activeInput_led);
                        SetInputLed_color(req.mCol,req.mRow, res.result.input);

                    }
                    break;
            }
        }

        private void SetInputLed_color(int col,int row,string input_type)
        {
            switch (input_type)
            {
                case "dvi1":
                case "dvi2":
                case "hdmi":
                case "ops":
                case "dp":
                    AllLedPanels[col, row].SetColor(Color.GreenYellow, WhichLed.activeInput_led);
                    break;
                default:
                    AllLedPanels[col, row].SetColor(Color.Blue, WhichLed.activeInput_led);
                    break;
            
            }
        
        }

        public void Responce(Cube_command_reqObj req, General_responce res)
        {
            if (isRecording)
            RecordguiControl.RecoderControllerResponce(req, res);

            if (req.requester_guy == cmd_requster.recoderControler)
            {
                //cubeGui1.CubeControllerResponce(req, res);
                StopAnimetion(req.mCol, req.mRow);
                return;
            }
            
            if (req.requester_guy == cmd_requster.cubeControler || req.requester_guy == cmd_requster.cubeControler_rpc_mode)
            {
                
                
                cubeGui1.CubeControllerResponce(req, res);
                if (req.requester_guy != cmd_requster.cubeControler_rpc_mode)
                StopAnimetion(req.mCol, req.mRow);
                return;
            }

            if (req.requester_guy == cmd_requster.wallmanagerself)
            {
               
                switch(req.cmdType)
                {
                    case commandType.cmd_fmw_update_spi:
                    case commandType.cmd_fmw_update_status_get:
                    case commandType.cmd_fmw_update_ps171:
                    case commandType.cmd_fmw_update_mstar:
                    case commandType.cmd_mo_get_log_msg_count_internal:
                    case commandType.cmd_dataBase_saveAll:
                    case commandType.cmd_mo_tigger_Diagnostics:
                    case commandType.cmd_mo_tigger_Diagnostics_status_get:
                    case commandType.cmd_mo_Get_Diagnostics_count_get:
                    case commandType.cmd_mo_Get_Diagnostics_msgs_get:
                        
                        
                        
                        break;
                    case commandType.cmd_gen_operation_state_StandBY_set:
                    case commandType.cmd_gen_operation_state_reboot_set:
                        ALLCubes[req.mCol, req.mRow].Disconnect();
                        StopAnimetion(req.mCol, req.mRow);
                        Reset_Led_panel(req.mCol, req.mRow);
                        break;

                    default:
                     StopAnimetion(req.mCol, req.mRow);
                break;
                }
                if(res.result != null)
                handle_result(req, res);
                return;
            }

            if (req.requester_guy == cmd_requster.wallControler)
            {

                wallControl.WallControllerResponce(req, res);
                StopAnimetion(req.mCol, req.mRow);
                return;
                
            }

            return;

            if (ALLCubes[req.mCol, req.mRow].iSAnyRequestPending())
            {
                //Thread.Sleep(1000);
                //AllloadingAniMetion[req.mCol, req.mRow].Active = true;
                return;
            }

            StopAnimetion(req.mCol, req.mRow);
            //Thread.Sleep(500);
            /*AllloadingAniMetion[req.mCol, req.mRow].Active = false;
            AllloadingAniMetion[req.mCol, req.mRow].Visible = false;
             * */


        
        }
        
        public void RawTransction(ReqRespDebugInfo obj)
        {
            if (isRecording)
                RecordguiControl.update_transction_views(obj);

            /*if (obj.cmd_type == reqResType.type_req)
                MessageBox.Show("-->" + obj.mIp + " " + obj.mCol + " " + obj.mRow + " "+ obj.mJson + " " + obj.Time);
            else
                MessageBox.Show("<--" + obj.mIp + " " + obj.mCol + " " + obj.mRow + " "+ obj.mJson + " " + obj.Time);
            */
        }

        #endregion


        #region Request/responce for cube GUI

        public int RecordControlWallRequest(Cube_command_reqObj req, string cmd_type)
        {
            Cube_command_reqObj obj;
            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {
                    if (ALLCubes[i, j].isConnected)
                    {
                        obj = new Cube_command_reqObj(req, i, j);

                        ALLCubes[i, j].Request(obj);
                        StartAnimetion(i, j, cmd_type);
                    }
                }
            }


            return 0;
        }

        public int RecorderExcuteRequest(Cube_command_reqObj req, string cmd_type)
        {

            if (currentSelection == SelectionType.sel_cube)
                RecordControlCubeRequest(req, cmd_type);
            else if (currentSelection == SelectionType.sel_wall)
                RecordControlWallRequest(req, cmd_type);
            else
                MessageBox.Show("Please Select Correct Cube or wall.");



            return 0;
        }

        public int RecordControlCubeRequest(Cube_command_reqObj req, string cmd_type)
        {

            int col, row;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                if (ALLCubes[col, row].isConnected)
                {

                    req.mCol = col;
                    req.mRow = row;

                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, cmd_type);
                }
                else
                    MessageBox.Show("This cube is Not Connected");


            }
            else
                MessageBox.Show("please Select the Correct cube");

            return 0;
        }

        public void GetRpcStatus(Cube_command_reqObj req, string cmd_type)
        {

            if (ALLCubes[req.mCol, req.mRow].isConnected)
            {
                ALLCubes[req.mCol, req.mRow].Request(req);
                //StartAnimetion(req.mCol, req.mRow, cmd_type);
            }
        
        }



        public int CubeControlRequest(Cube_command_reqObj req,string cmd_type)
        {


            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                CubeControlSingleCube_execution(req, cmd_type);


            }
            else if (currentSelection == SelectionType.sel_wall)
            {
                CubeControl_Wall_execution(req, cmd_type);
            }

            return 0;
        }
        public int CubeControl_Wall_execution(Cube_command_reqObj req, string cmd_type)
        {
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {

                    if (ALLCubes[col, row].isConnected)
                    {

                        req.mCol = col;
                        req.mRow = row;

                        ALLCubes[col, row].Request(req);
                        if (req.cmdType != commandType.cmd_artificial_sleep_set)
                            StartAnimetion(col, row, cmd_type);
                        else
                            RecordguiControl.RecoderControllerResponce(req, null);
                    }
                }

            }

            return 0;
        }


        public int CubeControlSingleCube_execution(Cube_command_reqObj req, string cmd_type)
        {

            int col, row;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                if (ALLCubes[col, row].isConnected)
                {

                    req.mCol = col;
                    req.mRow = row;

                    ALLCubes[col, row].Request(req);
                    if (req.cmdType != commandType.cmd_artificial_sleep_set)
                    StartAnimetion(col, row, cmd_type);
                    else
                        RecordguiControl.RecoderControllerResponce(req, null);

                        
                }
                else
                    MessageBox.Show("This cube is Not Connected");


            }
            else
                MessageBox.Show("please Select the Correct cube");

            return 0;
        }

        public int WallControlRequest(Cube_command_reqObj req, string cmd_type)
        {
            Cube_command_reqObj obj;
            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {
                    if (ALLCubes[i, j].isConnected)
                    {
                        obj = new Cube_command_reqObj(req,i,j);
                       
                        ALLCubes[i, j].Request(obj);
                        StartAnimetion(i, j, cmd_type);
                    }
                }
            }
            

            return 0;
        }

        #endregion

        #region Animetions and Led Controls

        public void StartAnimetion(int col,int row,string toopTip)
        {
            AllloadingAniMetion[col, row].Visible = true;
            AllloadingAniMetion[col, row].Active = true;

            AllLedPanels[col, row].SetColor(Color.GreenYellow, WhichLed.inProgress_led);
            AllLedPanels[col, row].StartBlink(500, WhichLed.inProgress_led);
            AllLedPanels[col, row].SetToolTipTitle(toopTip, WhichLed.inProgress_led);
        
        }

        public void StopAnimetion(int col, int row)
        {
            AllloadingAniMetion[col, row].Visible = false;
            AllloadingAniMetion[col, row].Active = false;
            AllLedPanels[col, row].StopBlink(WhichLed.inProgress_led);
            //AllLedPanels[col, row].StartBlink(0, 4);
            AllLedPanels[col, row].SetToolTipTitle("None", WhichLed.inProgress_led);
        
        }

        private void Reset_Led_panel(int col,int row)
        {
            for (int i = 1; i < 7; i++)
            {
                AllLedPanels[col, row].SetColor(Color.Gray, (WhichLed)(i));
                AllLedPanels[col, row].SetToolTipTitle("Unknown", (WhichLed)(i));
            }
 
        
        }



        #endregion

        #region Cube Right Click Event


        private void Cube_mnuUnSetIP_Click(object sender, EventArgs e)
        {
            string IP = "IP";
            
            int col, row;
            

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                ALLCubes[col, row].Disconnect();
                AllIplabels[col, row].Text = IP;
                AllIplabels[col, row].ForeColor = Color.Black;
                AllCubeLocLabels[col, row].Text = (row + 1) + "," + (col + 1);
                AllMstarverLabels[col, row].Text = "Mstar";

                ALLCubes[col, row].Unset_ip();
                Reset_Led_panel(col, row);
                StopAnimetion(col, row);
            }
            //MessageBox.Show(ret);
        }
        private bool AllReadyAssigned(string ip)
        {

            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {
                    if (ALLCubes[i, j].mIp == ip)
                    {
                       DialogResult result = MessageBox.Show("the " + ip + " is all ready assigned to cube " +(i+1).ToString() +"," + (j+1).ToString() + " Do you wish to re-assign it current selected","WARNING",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
                       if (result == System.Windows.Forms.DialogResult.Yes)
                       {
                           ALLCubes[i, j].Disconnect();
                           ALLCubes[i, j].Unset_ip();
                           AllIplabels[i, j].Text = "IP";
                           AllIplabels[i, j].ForeColor = Color.Black;


                           return false;
                       }

                        return true;
                    }

                }
            }

            return false;
        }
        private void Cube_mnuSetIP_Click(object sender, EventArgs e)
        {
            string IP = string.Empty;
            string Pass = string.Empty;

            
            int col, row;
            KP_inputBox.InputBox("Give Ip of cube", "IP", ref  IP);

            //KP_inputBox.LoginInputBox("Login Window (user Name/Password)", ref  IP, ref Pass);

           // MessageBox.Show(IP + " " + Pass);



            if(!AllReadyAssigned(IP))
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                if (!ALLCubes[col, row].isConnected)
                {

                    AllIplabels[col, row].Text = IP;

                    AllIplabels[col, row].ForeColor = Color.Red;
                    ALLCubes[col, row].set_ip(IP);
                }
                else
                    MessageBox.Show("This Cube is Connected please disconnect First");
            }
            //MessageBox.Show(ret);
        }


        private void GetMstar_fmw_version()
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    if (ALLCubes[col, row].isConnected)
                    {
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, 0, 0, commandType.cmd_fmw_mstar_version_get, null, null, null);
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get Operation Stat");
                    }
            }
        }

        private void GetMstar_fmw_version(int col, int row)
        {
            int id;

            //col = tlp.GetColumn(CurrentCubeControl);
            // row = tlp.GetRow(CurrentCubeControl);
            if (ALLCubes[col, row].isConnected)
            {
                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, 0, 0, commandType.cmd_fmw_mstar_version_get, null, null, null);
                ALLCubes[col, row].Request(req);
                StartAnimetion(col, row, "Get Operation Stat");
            }
        }

        private void GetOperationState()
        {
             int col, row,id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                {
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_get, null, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Get Operation Stat");
                    }
                }
        }

        private void GetOperationState(int col, int row)
        {
            int id;

            //col = tlp.GetColumn(CurrentCubeControl);
            // row = tlp.GetRow(CurrentCubeControl);
            if (ALLCubes[col, row].isConnected)
            {
                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_get, null, null, null);
                ALLCubes[col, row].Request(req);
                StartAnimetion(col, row, "Get Operation Stat");
            }
        }

        private void GetfmwVersion(int col,int row)
        {
            int  id;
            
                //col = tlp.GetColumn(CurrentCubeControl);
               // row = tlp.GetRow(CurrentCubeControl);
                if (ALLCubes[col, row].isConnected)
                {
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_mrc_spi_module_version_get, null, null, null);
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get fmw verison");
                }
        }

        private void GetfmwVersion()
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                if (ALLCubes[col, row].isConnected)
                {
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_mrc_spi_module_version_get, null, null, null);
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get Operation Stat");
                }
            }
        }


        private void GetSpecCalibHelth(int col, int row)
        {
            int  id;
            
                //col = tlp.GetColumn(CurrentCubeControl);
               // row = tlp.GetRow(CurrentCubeControl);
                if (ALLCubes[col, row].isConnected)
                {
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_cs_gobal_error_info_get_internal, null, null, null);
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get Spectral Calib Health");
                }
        }

        private void GetSpecCalibHelth()
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                if (ALLCubes[col, row].isConnected)
                {
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_cs_gobal_error_info_get_internal, null, null, null);
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get Spectral Calib Health");
                }
            }
        }

        

        

        

        private void GetActiveInput()
        {
            int col, row,id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_get_Active_input, null, null, null);

                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get Operation State");
                }
            }

        }
        private void GetActiveInput(int col, int row)
        {
            int id;

            id = identMgr.getNextIdent();
            Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_get_Active_input, null, null, null);

            if (ALLCubes[col, row].isConnected)
            {
                ALLCubes[col, row].Request(req);
                StartAnimetion(col, row, "Get Operation State");
            }

        }

        private void GetGaamStatus()
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_cs_gaam_upload_status_get, null, null, null);

                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Get Gaam State");
                }
            }

        }
        private void GetGaamStatus(int col, int row)
        {
            int id;

            id = identMgr.getNextIdent();
            Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_cs_gaam_upload_status_get, null, null, null);

            if (ALLCubes[col, row].isConnected)
            {
                ALLCubes[col, row].Request(req);
                StartAnimetion(col, row, "Get Gaam State");
            }

        }

        private void Cube_mnuRefresh_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("SetCube_mnuConnect_Click");
            int col, row;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube )
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                if (!ALLCubes[col, row].isConnected) return;
                
                //GetOperationState();
                //GetActiveInput();
                GetfmwVersion();
                //GetSpecCalibHelth();

            }
        }
        private void Cube_mnuConnect_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("SetCube_mnuConnect_Click");
            int col, row;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube )
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                
                if (COntrol_CheckAllService_CheckBox.Checked)
                    ALLCubes[col, row].Connect(Thread_optimization_check.Checked);
                else
                    ALLCubes[col, row].ConnectAny();

                if (!ALLCubes[col, row].isConnected) return;
                
                //GetOperationState();
                //GetActiveInput();
                GetfmwVersion();
                //GetSpecCalibHelth();

            }
        }
        private void Cube_mnuDisConnect_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("SetCube_mnuConnect_Click");
            int col, row;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                ALLCubes[col, row].Disconnect();
                AllCubeLocLabels[col, row].Text = (row + 1) + "," + (col + 1);
                StopAnimetion(col, row);
                Reset_Led_panel(col, row);
            }
        }


        private void Cube_mnuResetSTDP_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("SetCube_mnuConnect_Click");
            int col, row,id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                id = identMgr.getNextIdent();
                string[] param = new string[2];
                param[0] = "752";
                param[1] = "1";
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fpga_reg_set, param, null, null);

                if (ALLCubes[col, row].isConnected)
                          ALLCubes[col, row].Request(req);
                
                param = new string[2];
                param[0] = "752";
                param[1] = "0";

                req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fpga_reg_set, param, null, null);
                
                if (ALLCubes[col, row].isConnected)
                            ALLCubes[col, row].Request(req);

                StartAnimetion(col, row, "Get Spectral Calib Health");
                
            }
        }

        private void Cube_mnuTrigger_diagnostics_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("SetCube_mnuConnect_Click");
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                if (!ALLCubes[col, row].isConnected) return;

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_mo_tigger_Diagnostics, null, null, null);
                 ALLCubes[col, row].Request(req);
                StartAnimetion(col, row, "Tigger Diagnostics");

            }
        }


        private void Cube_mnuShow_diagnostics_result_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("SetCube_mnuConnect_Click");
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                if (!ALLCubes[col, row].isConnected) return;

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_mo_Get_Diagnostics_count_get, null, null, null);
                ALLCubes[col, row].Request(req);
                StartAnimetion(col, row, "Show Diagnostics Count");

            }
        }
        

        

        private void Cube_mnuUpdate_spi_flash_Click(object sender, EventArgs e)
        {
           // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");
            int col, row, id;

            DialogResult ret = MessageBox.Show("Current version of OVD/KVD firmware does not support failsafe upgrade mechanism,Please ensure that power to panel is not interrupted during this 3 minutes of upgrade time.Do you want to continue?","WARNING!!",  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ret != System.Windows.Forms.DialogResult.Yes) return;

            if (!Wall_UoloadMethod_tftp_radio.Checked)
            {
                ret = openFileDialog1.ShowDialog();
                if (ret != System.Windows.Forms.DialogResult.OK) return;
            }
                
                    if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                    {
                        col = tlp.GetColumn(CurrentCubeControl);
                        row = tlp.GetRow(CurrentCubeControl);
                        string[] parm = new string[4];
                        parm[0] = "MrcSpiImg";
                        parm[1] = openFileDialog1.FileName;

                        if (Wall_UoloadMethod_Cgi_radio.Checked)
                            parm[2] = "cgi";
                        else if (Wall_UoloadMethod_tftp_radio.Checked)
                        {
                            string mMyHost = System.Net.Dns.GetHostName();
                            parm[2] = "tftp";
                            parm[3] = System.Net.Dns.GetHostByName(mMyHost).AddressList[0].ToString(); ;
                            KP_inputBox.InputBox("Ip of tftp Server", "IP", ref parm[3]);
                        }
                        else
                            parm[2] = "scp";


                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fmw_update_spi, parm, null, null);
                        if (ALLCubes[col, row].isConnected)
                        {
                            ALLCubes[col, row].Request(req);
                            StartAnimetion(col, row, "Spi Raw Flash Update");
                        }
                        else
                            MessageBox.Show("Please Connect First");
                        //AllloadingAniMetion[col, row].Visible = true;
                        //AllloadingAniMetion[col, row].Active = true;
                    }
        }

        private void Cube_mnuUpdate_mstar_flash_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (!Wall_UoloadMethod_tftp_radio.Checked)
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName != "")
            {
                if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                {
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    string[] parm = new string[4];
                    parm[0] = "MrcMstar";
                    parm[1] = openFileDialog1.FileName;

                    if (Wall_UoloadMethod_Cgi_radio.Checked)
                        parm[2] = "cgi";
                    else if (Wall_UoloadMethod_tftp_radio.Checked)
                    {
                        string mMyHost = System.Net.Dns.GetHostName();
                        parm[2] = "tftp";
                        parm[3] = System.Net.Dns.GetHostByName(mMyHost).AddressList[0].ToString(); ;
                        KP_inputBox.InputBox("Ip of tftp Server", "IP", ref parm[3]);
                    }
                    else
                        parm[2] = "scp";

                    id = identMgr.getNextIdent();
                    //Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_mstar, parm);
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fmw_update_mstar, parm, null, null);
                    if (ALLCubes[col, row].isConnected)
                    {
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Mstar Update");
                    }
                    /*AllloadingAniMetion[col, row].Visible = true;
                    AllloadingAniMetion[col, row].Active = true;
                     * */
                }
            }
            else
                MessageBox.Show("Please select the correct fmw file for mstar flash");

            //rootGui.Responce(
        }

        private void Cube_mnuUpdate_ps171_Bank2_flash_Click(object sender, EventArgs e)
        {
            int col, row, id;
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName != "")
            {
                if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                {
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    string[] parm = new string[3];
                    parm[0] = "MrcPs171";
                    parm[1] = openFileDialog1.FileName;
                    parm[2] = "cgi";
                    id = identMgr.getNextIdent();
                    //Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_ps171, parm);
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fmw_update_ps171, parm, null, null);
                    if (ALLCubes[col, row].isConnected)
                    {
                        ALLCubes[col, row].Request(req);
                        AllloadingAniMetion[col, row].Visible = true;
                        AllloadingAniMetion[col, row].Active = true;
                    }
                }
            }
            else
                MessageBox.Show("Please select the correct fmw file for ps171 flash");

        }


        private void Cube_mnuUpdate_edid_dvi1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cube_mnuUpdate_edid_dvi1_Click");
        }

        private void Cube_mnuUpdate_edid_dvi2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cube_mnuUpdate_edid_dvi2_Click");
        }

        private void Cube_mnuUpdate_edid_hdmi_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cube_mnuUpdate_edid_hdmi_Click");
        }


        private void Cube_mnuUpdate_edid_dp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cube_mnuUpdate_edid_dp_Click");
        }

        private void Cube_mnuUpdate_edid_ops_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cube_mnuUpdate_edid_ops_Click");
        }

        private void Cube_mnuUpdate_ps171_Bank3_flash_Click(object sender, EventArgs e)
        {
            int col, row, id;
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName != "")
            {
                if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                {
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    string[] parm = new string[3];
                    parm[0] = "MrcPs171";
                    parm[1] = openFileDialog1.FileName;
                    parm[2] = "bank3";
                    id = identMgr.getNextIdent();
                    //Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_ps171, parm);
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fmw_update_ps171, parm, null, null);
                    if (ALLCubes[col, row].isConnected)
                    {
                        ALLCubes[col, row].Request(req);
                        AllloadingAniMetion[col, row].Visible = true;
                        AllloadingAniMetion[col, row].Active = true;
                    }
                }
            }
            else
                MessageBox.Show("Please select the correct fmw file for ps171 flash");

        }

        private void Cube_mnuUpdate_mmc_flash_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Cube_mnuUpdate_mmc_flash_Click");
        }


       

        private void DoMove(Control current_p,Control CutSwap_p)
        {
            int col, row;
            string CutIp;

            col = tlp.GetColumn(CutSwap_p);
            row = tlp.GetRow(CutSwap_p);

            CutIp = ALLCubes[col, row].mIp;
            ALLCubes[col, row].Disconnect();
            ALLCubes[col, row].Unset_ip();
            AllIplabels[col, row].Text = "IP";
            AllIplabels[col, row].ForeColor = Color.Black;
            AllMstarverLabels[col, row].Text = "Mstar";
            Reset_Led_panel(col, row);
            AllCubeLocLabels[col, row].Text = (row + 1) + "," + (col + 1);

            col = tlp.GetColumn(current_p);
            row = tlp.GetRow(current_p);

            ALLCubes[col, row].Disconnect();
            ALLCubes[col, row].set_ip(CutIp);
            AllIplabels[col, row].Text = CutIp;
            AllIplabels[col, row].ForeColor = Color.Red;
            
            //ALLCubes[col, row].Connect();

            CutSwap_p.BackColor = CubeBackCol;
            CutSwap_p = null;

            currentSelection = SelectionType.sel_cube;
            if (ALLCubes[col, row].isConnected)
            {
                GetOperationState();
                GetActiveInput();
                GetfmwVersion();
                GetSpecCalibHelth();
            }
            
            //CurrentCutSwapControl = null;


        
        }


        private void DoSwap(Control current_p, Control CutSwap_p)
        {
            int SwapCol, SwapRow;
            int CurCol, CurRow;
            string CutIp, CurrentIp;
            string SwapMstarVer,CurMstarVer;

            SwapCol = tlp.GetColumn(CutSwap_p);
            SwapRow = tlp.GetRow(CutSwap_p);

            CutIp = ALLCubes[SwapCol, SwapRow].mIp;
            SwapMstarVer = AllMstarverLabels[SwapCol, SwapRow].Text;

            CurCol = tlp.GetColumn(current_p);
            CurRow = tlp.GetRow(current_p);

            Reset_Led_panel(SwapCol, SwapRow);
            Reset_Led_panel(CurCol, CurRow);

            CurrentIp = ALLCubes[CurCol, CurRow].mIp;
            CurMstarVer = AllMstarverLabels[CurCol, CurRow].Text;

            ALLCubes[SwapCol, SwapRow].Disconnect();
            ALLCubes[SwapCol, SwapRow].set_ip(CurrentIp);
            AllIplabels[SwapCol, SwapRow].Text = CurrentIp;
            AllCubeLocLabels[SwapCol, SwapRow].Text = (SwapRow + 1) + "," + (SwapCol + 1);
            AllMstarverLabels[SwapCol, SwapRow].Text = CurMstarVer;
           // ALLCubes[SwapCol, SwapRow].Connect();
            CutSwap_p.BackColor = CubeBackCol;
            

            ALLCubes[CurCol, CurRow].Disconnect();
            ALLCubes[CurCol, CurRow].set_ip(CutIp);
            AllIplabels[CurCol, CurRow].Text = CutIp;
            AllCubeLocLabels[CurCol, CurRow].Text = (CurRow + 1) + "," + (CurCol + 1);
            AllMstarverLabels[CurCol, CurRow].Text = SwapMstarVer;
            //ALLCubes[CurCol, CurRow].Connect();
            
            CutSwap_p = null;

          currentSelection = SelectionType.sel_cube;
            if (ALLCubes[SwapCol, SwapRow].isConnected)
            {
                GetOperationState(SwapCol, SwapRow);
                GetActiveInput(SwapCol, SwapRow);
                GetfmwVersion(SwapCol, SwapRow);
                GetSpecCalibHelth(SwapCol, SwapRow);
            }

            if (ALLCubes[CurCol, CurRow].isConnected)
            {
                GetOperationState(CurCol, CurRow);
                GetActiveInput(CurCol, CurRow);
                GetfmwVersion(CurCol, CurRow);
                GetSpecCalibHelth(CurCol, CurRow);
            }
            

        }

        private void Cube_mnu_Cut_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Cube_mnuUpdate_OPState_ON_Click");
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                CurrentCubeControl.BackColor = CutSwap;
                CurrentCutSwapControl = CurrentCubeControl;
                currentSelection = SelectionType.sel_cube_cut;
            }
        }

        private void Cube_mnu_Paste_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Cube_mnuUpdate_OPState_ON_Click");
            
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube_cut)
            {
                DoMove(CurrentCubeControl,CurrentCutSwapControl);
                
            }
        }


        private void Cube_mnu_Swap_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Cube_mnuUpdate_OPState_ON_Click");

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube_cut)
            {
                DoSwap(CurrentCubeControl, CurrentCutSwapControl);
                currentSelection = SelectionType.sel_cube;
            }
        }

        private void Cube_mnuEnable_logs_Click(object sender, EventArgs e)
        {
            int id;
            int col, row;
            string[] parm = new string[1];
            parm[0] = "enable";

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                if (ALLCubes[col, row].isConnected)
                {
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_img_Detail_Log_flag_set, parm, null, null);
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Detail Log Flag");

                    //GetOperationState(col, row); //KP
                    //GetActiveInput(col, row);
                    //GetfmwVersion(col, row);
                }
            }
           

        }

        private void Cube_mnuDisable_logs_Click(object sender, EventArgs e)
        {
            int id,col,row;
            string[] parm = new string[1];
            parm[0] = "disable";
            
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);


                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_img_Detail_Log_flag_set, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set Detail Log Flag");

                        //GetOperationState(col, row); //KP
                        //GetActiveInput(col, row);
                        //GetfmwVersion(col, row);
                    }
             }
            


        }

        private void Cube_mnuDownloadLog_Click(object sender, EventArgs e)
        {
            int id,col,row;
            //DialogResult ret = MessageBox.Show("This action will a lot of time Sit Relax and Enjoy your coffee. Do you wish to Continue ?","WARNING!!", MessageBoxButtons.YesNo,  MessageBoxIcon.Warning);

            DialogResult ret = folderBrowserDialog1.ShowDialog();

            if (ret == System.Windows.Forms.DialogResult.OK)
            {
                mLogFileName = folderBrowserDialog1.SelectedPath;
            }

            if (ret != System.Windows.Forms.DialogResult.OK) return;

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);

                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, 0, 0, commandType.cmd_mo_get_log_msg_count_internal, null, textBox1, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Downloading Logs");
                    }

             }

            

        }

       


        private void Cube_mnuUpdate_OPState_ON_Click(object sender, EventArgs e)
        {
            int col, row, id;
            
                if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                {
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    string[] parm = new string[1];
                    parm[0] = "on";
                    
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_set, parm, null, null);
                    if (ALLCubes[col, row].isConnected)
                    {
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Operation Set On");
                        GetOperationState(col, row);
                    }
                    //GetActiveInput(col, row);
                    //GetfmwVersion(col, row);
                    
                }
            
        }


        private void Cube_mnu_setInput_dvi1_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "dvi1";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");
                    
                }
                
            }

        }

        private void Cube_mnu_setInput_dvi2_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "dvi2";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_hdmi_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "hdmi";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_ops_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "ops";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_dp_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "dp";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_Scan_dvi1_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "scandvi1";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_Scan_dvi2_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "scandvi2";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_Scan_hdmi_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "scanhdmi";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_Scan_dp_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "scandp";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_Scan_ops_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "scanops";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_setInput_Scan_oBoard_Click(object sender, EventArgs e)
        {
            int col, row, id;
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "scanonboard";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Set Input");

                }

            }

        }

        private void Cube_mnu_Identify_Click(object sender, EventArgs e)
        {
            int col, row, id;

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "on";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_cube_Blink_identify, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Blink Identify");
                }
                

            }

        }

        public void SetWallidle()
        {
            Wall_mnuUpdate_OPState_IDEL_Click(null, null);
        
        }

        public void SetWallOn()
        {
            Wall_mnuUpdate_OPState_ON_Click(null, null);

        }

        private void Cube_mnuUpdate_OPState_IDEL_Click(object sender, EventArgs e)
        {
            int col, row, id;
            
                if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
                {
                    col = tlp.GetColumn(CurrentCubeControl);
                    row = tlp.GetRow(CurrentCubeControl);
                    string[] parm = new string[1];
                    parm[0] = "idle";
                    
                    id = identMgr.getNextIdent();
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_set, parm, null, null);
                    if (ALLCubes[col, row].isConnected)
                    {
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Operation Set idle");
                        GetOperationState(col, row);
                    }
                    //GetActiveInput(col, row);
                   // GetfmwVersion(col, row);
                    
                }
            
                

                /*Thread t = new Thread(ZeroCOnf);
                t.Start();
                */

               

            
        }

        private void ZeroCOnf()
        {
            string[] arg = new string[1];
            while (true)
            {
                MZClient.Main_MY(arg);
            }
        
        }

        private void Cube_mnuUpdate_OPState_StandBy_Click(object sender, EventArgs e)
        {
            int col, row, id;

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "standby";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_StandBY_set, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Operation Set standBy");
                }

            }
           
        }

        private void Cube_mnuUpdate_OPState_Reboot_Click(object sender, EventArgs e)
        {
            int col, row, id;

            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                string[] parm = new string[1];
                parm[0] = "reboot";

                id = identMgr.getNextIdent();
                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_reboot_set, parm, null, null);
                if (ALLCubes[col, row].isConnected)
                {
                    ALLCubes[col, row].Request(req);
                    StartAnimetion(col, row, "Operation Set reboot");
                }

            }

        }

        private void Cube_mnuUpdate_Send_wakeOnLAN_Click(object sender, EventArgs e)
        {
            int col, row;
            //MessageBox.Show("Cube_mnuUpdate_Send_wakeOnLAN_Click");
            
            if (CurrentCubeControl != null && currentSelection == SelectionType.sel_cube)
            {
                col = tlp.GetColumn(CurrentCubeControl);
                row = tlp.GetRow(CurrentCubeControl);
                ALLCubes[col, row].wakeOnlan();
            }
           
        }

        #endregion

        #region Wall Right Click Events

        private void Wall_mnuUpdate_edid_dvi1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Wall_mnuUpdate_edid_dvi1_Click");
        }

        private void Wall_mnuUpdate_edid_dvi2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Wall_mnuUpdate_edid_dvi2_Click");
        }

        private void Wall_mnuUpdate_edid_hdmi_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Wall_mnuUpdate_edid_hdmi_Click");
        }


        private void Wall_mnuUpdate_edid_dp_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Wall_mnuUpdate_edid_dp_Click");
        }

        private void Wall_mnuUpdate_edid_ops_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Wall_mnuUpdate_edid_ops_Click");
        }

        private void Wall_mnuSet_SaveALL_inputs_Click(object sender, EventArgs e)
        {
            //string fileName = localDir + "//LastAllInputs.db";
            GuiBoxArray gui = null;
            int id;
            mLastInputRecord = localDir + "\\LastInputs.db";

            FileInfo MyFile = new FileInfo(mLastInputRecord);
            if (MyFile.Exists)
                MyFile.Delete();

           



            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                   
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_get_input_selected_internal, null, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Get Selected Input");


                    }
                }
            }

            

        }

        private void Wall_mnuSet_RestoreALL_inputs_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Wall_mnuSet_RestoreALL_inputs_Click");
            mLastInputRecord = localDir + "\\LastInputs.db";

            byte[] Inputs = ReadFileIps(mLastInputRecord);
            if (Inputs == null) return;
            string AllIputs = System.Text.ASCIIEncoding.ASCII.GetString(Inputs);
            string[] SplitedIps = AllIputs.Split('\n');
            input_record inputs_rec;
            foreach (string str in SplitedIps)
            {
                if (str != "")
                {
                    inputs_rec = JsonConvert.DeserializeObject<input_record>(str);
                    string[] parm = new string[1];
                    parm[0] = inputs_rec.input;
                    Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.cubeControler, 0, 0, commandType.cmd_set_input_selected, parm, null, null);
                    if (ALLCubes[inputs_rec.pos_col, inputs_rec.pos_row].isConnected)
                    {
                        ALLCubes[inputs_rec.pos_col, inputs_rec.pos_row].Request(req);
                        StartAnimetion(inputs_rec.pos_col, inputs_rec.pos_row, "Set input");
                    }
                }
            }


        }




        private void Wall_mnuSet_input_dvi1_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "dvi1";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuSet_input_dvi2_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "dvi2";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuSet_input_hdmi_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "hdmi";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuSet_input_dp_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "dp";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuSet_input_ops_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "ops";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_onboard_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "onboard";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_scan_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scandvi1";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_scan_dvi1_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scandvi1";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_scan_dvi2_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scandvi2";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_scan_hdmi_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scanhdmi";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }


        }

        private void Wall_mnuUSet_input_scan_ops_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scanops";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_scan_dp_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scandp";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUSet_input_scan_onboard_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "scanonboard";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_set_input_selected, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set input");
                    }
                }
            }
        }

        private void Wall_mnuUpdate_OPState_ON_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");
            int id;
            string[] parm = new string[1];
                    parm[0] = "on";
                    for (int col = 0; col < mCol; col++)
                    {
                        for (int row = 0; row < mRow; row++)
                        {
                            
                            if (ALLCubes[col, row].isConnected)
                            {
                                id = identMgr.getNextIdent();
                                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_set, parm, null, null);
                                ALLCubes[col, row].Request(req);
                                StartAnimetion(col, row, "Set Operation On");
                                
                                GetOperationState(col, row); //KP
                                //GetActiveInput(col, row);
                                //GetfmwVersion(col, row);
                            }
                        }
                    }

        }

        private void Wall_mnuUpdate_OPState_IDEL_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");
            int id;
            string[] parm = new string[1];
            parm[0] = "idle";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_set, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Operation idle");
                        
                        GetOperationState(col, row); //KP
                        //GetActiveInput(col, row);
                        //GetfmwVersion(col, row);
                        
                    }
                }
            }

        }

        private void Wall_mnuUpdate_OPState_standBy_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");
            int id;
            string[] parm = new string[1];
            parm[0] = "standby";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_StandBY_set, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Operation standby"); 
                        
                    }
                }
            }

        }

        private void Wall_mnuUpdate_OPState_reboot_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");
            int id;
            string[] parm = new string[1];
            parm[0] = "reboot";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_gen_operation_state_reboot_set, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Operation reboot"); 
                    }
                }
            }

        }

        private void Wall_mnuUpdate_spi_flash_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");

            int id;
            bool doit = true;

            
            DialogResult ret = MessageBox.Show("Current version of OVD/KVD firmware does not support failsafe upgrade mechanism,Please ensure that power to panel is not interrupted during this 3 minutes of upgrade time.Do you want to continue?", "WARNING!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ret != System.Windows.Forms.DialogResult.Yes) return;

            if (!Wall_UoloadMethod_tftp_radio.Checked)
            {
                ret = openFileDialog1.ShowDialog();
                if (ret != System.Windows.Forms.DialogResult.OK) return;
            }


            string[] parm = new string[4];
                    parm[0] = "MrcSpiImg";
                    parm[1] = openFileDialog1.FileName;

                    if (Wall_UoloadMethod_Cgi_radio.Checked)
                        parm[2] = "cgi";
                    else if (Wall_UoloadMethod_tftp_radio.Checked)
                    {
                        string mMyHost = System.Net.Dns.GetHostName();
                        parm[2] = "tftp";
                        parm[3] = System.Net.Dns.GetHostByName(mMyHost).AddressList[0].ToString(); ;
                        KP_inputBox.InputBox("Ip of tftp Server", "IP", ref parm[3]);
                    }
                    else
                        parm[2] = "scp";



                    for (int col = 0; col < mCol; col++)
                    {
                        for (int row = 0; row < mRow; row++)
                        {
                            if (ALLCubes[col, row].mIp != string.Empty)
                            {
                                id = identMgr.getNextIdent();
                                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fmw_update_spi, parm, null, null);
                                //Cube_command_reqObj req = new Cube_command_reqObj( id, col, row, commandType.cmd_fmw_update_spi, parm);
                                if (ALLCubes[col, row].isConnected)
                                {
                                    ALLCubes[col, row].Request(req);
                                    StartAnimetion(col, row, "Raw Spi Fmw update");
                                }
                                //AllloadingAniMetion[col, row].Visible = true;
                                //AllloadingAniMetion[col, row].Active = true;
                            }
                        }
                    }

                //}
               // else
                 //   MessageBox.Show("Please select the correct fmw file for spi flash");
            
        }

        private void Wall_mnuUpdate_mstar_flash_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");

            int id;
            DialogResult ret ;
            openFileDialog1.FileName = string.Empty;
            
            if (!Wall_UoloadMethod_tftp_radio.Checked)
            {
                ret = openFileDialog1.ShowDialog();
                if (ret != System.Windows.Forms.DialogResult.OK) return;
            }

            
                    string[] parm = new string[4];
                    parm[0] = "MrcMstar";
                    parm[1] = openFileDialog1.FileName;

                    if (Wall_UoloadMethod_Cgi_radio.Checked)
                        parm[2] = "cgi";
                    else if (Wall_UoloadMethod_tftp_radio.Checked)
                    {
                        string mMyHost = System.Net.Dns.GetHostName();
                        parm[2] = "tftp";
                        parm[3] = System.Net.Dns.GetHostByName(mMyHost).AddressList[0].ToString(); ;
                        KP_inputBox.InputBox("Ip of tftp Server", "IP", ref parm[3]);
                    }
                    else
                        parm[2] = "scp";


                    for (int col = 0; col < mCol; col++)
                    {
                        for (int row = 0; row < mRow; row++)
                        {
                            if (ALLCubes[col, row].isConnected)
                            {
                                id = identMgr.getNextIdent();
                               // Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_mstar, parm);
                                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_fmw_update_mstar, parm, null, null);
                                ALLCubes[col, row].Request(req);
                                StartAnimetion(col, row, "Mstar Update");
                                /*AllloadingAniMetion[col, row].Visible = true;
                                AllloadingAniMetion[col, row].Active = true;
                                 * */
                            }
                        }
                    }
                
            
        }
        
        private void Wall_mnuUpdate_mmc_flash_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Wall_mnuUpdate_mmc_flash_Click");

        }

        private void Wall_mnuUpdate_ps171_bank2_flash_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");

            int id;
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName != "")
            {
                string[] parm = new string[3];
                parm[0] = "MrcPs171";
                parm[1] = openFileDialog1.FileName;
                parm[2] = "bank2";

                for (int col = 0; col < mCol; col++)
                {
                    for (int row = 0; row < mRow; row++)
                    {
                        if (ALLCubes[col, row].isConnected)
                        {
                            id = identMgr.getNextIdent();
                            Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_ps171, parm);
                            ALLCubes[col, row].Request(req);
                            StartAnimetion(col, row, "PS171 programing");
                        }
                    }
                }

            }
            else
                MessageBox.Show("Please select the correct fmw file for ps171 flash", "BABA ji ka thullu Abe file  select kar", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }

        private void Wall_mnuUpdate_ps171_bank3_flash_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Cube_mnuUpdate_spi_flash_Click");

            int id;
            openFileDialog1.ShowDialog();

            if (openFileDialog1.FileName != "")
            {
                string[] parm = new string[3];
                parm[0] = "MrcPs171";
                parm[1] = openFileDialog1.FileName;
                parm[2] = "bank3";

                for (int col = 0; col < mCol; col++)
                {
                    for (int row = 0; row < mRow; row++)
                    {
                        if (ALLCubes[col, row].isConnected)
                        {
                            id = identMgr.getNextIdent();
                            Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_ps171, parm);
                            ALLCubes[col, row].Request(req);
                            /*AllloadingAniMetion[col, row].Visible = true;
                            AllloadingAniMetion[col, row].Active = true;
                             * */
                            StartAnimetion(col, row, "PS171 programing");
                        }
                    }

                }

            }
            else
                MessageBox.Show("Please select the correct fmw file for ps171 flash", "BABA ji ka thullu Abe file  select kar", MessageBoxButtons.OK, MessageBoxIcon.Error);

        }


        //Wall_mnuApplyWallConfig_Click      

        private void Wall_mnuApplyWallConfig_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Wall_mnuConnect_Click");

            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {

                    ALLCubes[i, j].ApplyWallConfig();
                }

            }
            

        }


        private void Wall_mnuRefresh_Click(object sender, EventArgs e)
        {
           // MessageBox.Show("Wall_mnuConnect_Click");

            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {

                    if (ALLCubes[i, j].isConnected)
                    {
                        //GetOperationState(i, j); //KP
                       // GetActiveInput(i, j);
                        GetfmwVersion(i, j);
                       // GetSpecCalibHelth(i, j);
                    }
                }

            }
            
        }

        private void Wall_mnuSaveAll_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Wall_mnuConnect_Click");
            int id;

            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {

                    if (!ALLCubes[col, row].isConnected) return;
                    

                        id = identMgr.getNextIdent();
                        id = identMgr.getNextIdent();
                        // Cube_command_reqObj req = new Cube_command_reqObj(id, col, row, commandType.cmd_fmw_update_mstar, parm);
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_dataBase_saveAll, null, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Save All");
                    
                }
            }
        }



        private void Wall_mnuConnect_Click(object sender, EventArgs e)
        {
           // MessageBox.Show("Wall_mnuConnect_Click");

            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {
                    
                    if(!ALLCubes[i, j].isConnected)
                        if (COntrol_CheckAllService_CheckBox.Checked)
                            ALLCubes[i, j].Connect(Thread_optimization_check.Checked);
                        else
                            ALLCubes[i, j].ConnectAny();
                    Thread.SpinWait(1000000);

                    if (ALLCubes[i, j].isConnected)
                    {
                        //GetOperationState(i, j); //KP
                       // GetActiveInput(i, j);
                        GetfmwVersion(i, j);
                       // GetSpecCalibHelth(i, j);
                    }
                }

            }
            
        }

        private void Wall_mnuDisConnect_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Wall_mnuDisConnect_Click");

            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {

                    ALLCubes[col, row].Disconnect();
                    StopAnimetion(col, row);
                    Reset_Led_panel(col, row);
                    AllCubeLocLabels[col, row].Text = (row + 1) + "," + (col + 1);
                }

            }

        }

        private void Wall_mnuUnSetIp_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Wall_mnuDisConnect_Click");

            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {

                    ALLCubes[i, j].Disconnect();
                    ALLCubes[i, j].Unset_ip();
                    AllIplabels[i, j].Text = "IP";
                    Reset_Led_panel(i, j);
                    AllCubeLocLabels[i, j].Text = (j + 1) + "," + (i + 1);
                    AllMstarverLabels[i, j].Text = "Mstar";
                }

            }

        }

        private void Wall_mnuEnable_logs_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "enable";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {

                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_img_Detail_Log_flag_set, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set Detail Log Flag");

                        //GetOperationState(col, row); //KP
                        //GetActiveInput(col, row);
                        //GetfmwVersion(col, row);
                    }
                }
            }


        }

        private void Wall_mnuDisable_logs_Click(object sender, EventArgs e)
        {
            int id;
            string[] parm = new string[1];
            parm[0] = "disable";
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {

                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_img_Detail_Log_flag_set, parm, null, null);
                        ALLCubes[col, row].Request(req);
                        StartAnimetion(col, row, "Set Detail Log Flag");

                        //GetOperationState(col, row); //KP
                        //GetActiveInput(col, row);
                        //GetfmwVersion(col, row);
                    }
                }
            }


        }

        private void Wall_mnuTrigger_diagnostics_Click(object sender, EventArgs e)
        {
            int id;
            //DialogResult ret = MessageBox.Show("This action will a lot of time Sit Relax and Enjoy your coffee. Do you wish to Continue ?","WARNING!!", MessageBoxButtons.YesNo,  MessageBoxIcon.Warning);

            //DialogResult ret = folderBrowserDialog1.ShowDialog();

            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, col, row, commandType.cmd_mo_tigger_Diagnostics, null, null, null);
                        ALLCubes[col, row].Request(req);
                        /*AllloadingAniMetion[col, row].Visible = true;
                        AllloadingAniMetion[col, row].Active = true;
                         * */
                        StartAnimetion(col, row, "Tigging Diagnostics");
                    }

                }

            }
        }

        private void Wall_mnuDownloadLog_Click(object sender, EventArgs e)
        {
            int id;
            //DialogResult ret = MessageBox.Show("This action will a lot of time Sit Relax and Enjoy your coffee. Do you wish to Continue ?","WARNING!!", MessageBoxButtons.YesNo,  MessageBoxIcon.Warning);

            DialogResult ret = folderBrowserDialog1.ShowDialog();

            if (ret == System.Windows.Forms.DialogResult.OK)
            {
                mLogFileName = folderBrowserDialog1.SelectedPath;
            }

            if (ret != System.Windows.Forms.DialogResult.OK) return;

            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (ALLCubes[col, row].isConnected)
                    {
                        id = identMgr.getNextIdent();
                        Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, 0, 0, commandType.cmd_mo_get_log_msg_count_internal, null, textBox1, null);
                        ALLCubes[col, row].Request(req);
                        /*AllloadingAniMetion[col, row].Visible = true;
                        AllloadingAniMetion[col, row].Active = true;
                         * */
                        StartAnimetion(col, row, "Downloading Logs");
                    }
                    
                }

            }
        }

       
        
        private void Wall_mnuUpdate_Send_wakeOnLAN_Click(object sender, EventArgs e)
        {
            // MessageBox.Show("Wall_mnuConnect_Click");

            for (int i = 0; i < mCol; i++)
            {
                for (int j = 0; j < mRow; j++)
                {

                    ALLCubes[i, j].wakeOnlan();
                }

            }

        }

        #endregion

        #region GUI event
        private void WallManager_FormClosed(object sender, FormClosedEventArgs e)
        {
            for (int i = 0; i < mCol; i++)
            {
                    for (int j = 0; j < mRow; j++)
                    {
                        if (ALLCubes[i,j].isConnected)
                        ALLCubes[i,j].Disconnect();
                    }

            }

            isRespWorkerRunning = false;
            if (Rev_responce_worker != null)
            Rev_responce_worker.Abort();
            Rest_server_stop();
            notifyIcon1.Visible = false;
            notifyIcon1.Dispose();

        }
        #endregion

        #region string to Byte Array
        public static byte C2b(char c)
        {
            if ((int)c < 256) return (byte)c;
            throw new Exception("character overflows a byte");
        }
        public static byte[] S2b(string value)
        {
            byte[] buffer = new byte[value.Length];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = C2b(value[i]);
            }

            return buffer;
        }
        #endregion

        #region File operations
        private void WriteToFIle(string fileName, string data)
        {
            FileStream FStream = null;
            FStream = File.OpenWrite(fileName);
            FStream.Seek(0, SeekOrigin.Begin);


            FStream.Write(S2b(data), 0, data.Length);

            FStream.Close();

        }
        #endregion

        #region Drag and drop testing

        public  Boolean isAlphaNumeric(string strToCheck)
        {
            Regex rg = new Regex(@"^[a-zA-Z0-9\s,]*$");
            return rg.IsMatch(strToCheck);
        }
        private void saveWallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int myInt;
            byte[] NotapasNewline = new byte[2];

            NotapasNewline[0] = (byte)'\r';
            NotapasNewline[1] = (byte)'\n';

            saveFileDialog1.Filter = "WallConfig File|*.wall";
            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName != "")
            {
                //WallConfig_obj obj = new WallConfig_obj(ALLCubes);
                //string json = JsonConvert.SerializeObject(obj);
                FileStream FStream = null;
                FStream = File.OpenWrite(saveFileDialog1.FileName);
                FStream.Seek(0, SeekOrigin.Begin);


                //int.TryParse(someString, out myInt);
                foreach (NSLcube obj in ALLCubes)
                {
                    //if (obj.mDispSerialNumber == string.Empty || !Microsoft.VisualBasic.Information.IsNumeric(obj.mDispSerialNumber))
                    if (obj.mDispSerialNumber == string.Empty || !int.TryParse(obj.mDispSerialNumber, out myInt))
                    {
                        obj.mDispSerialNumber = obj.mMacAddress1.Replace(":", "");
                    }

                    string json = JsonConvert.SerializeObject(obj);
                    FStream.Write(S2b(json), 0, json.Length);
                    FStream.Write(NotapasNewline, 0, 2);
                }

                FStream.Close();
            }

        }

        int dragOffsetX, dragOffsetY;
        bool isDragging = false;
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                PictureBox letter = (PictureBox)sender;

                letter.BringToFront();
                letter.Top += (e.Y - dragOffsetY);
                letter.Left += (e.X - dragOffsetX);
            }

        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (sender is PictureBox && e.Button == MouseButtons.Left)
            {
                isDragging = true;
                dragOffsetX = e.X;
                dragOffsetY = e.Y;
            }
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            isDragging = false;

        }

        #endregion

        #region Wall Commands
        private void Wal_Img_MercurySetSourceSelected_butt_Click(object sender, EventArgs e)
        {

            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    //if(ALLCubes[col,row].isConnected)
                       // Img_SetSourceSeleted_wall(col, row);
                }
            }

            


        }

        #endregion


        private void General_Init_from_DB()
        {
            Db = Kpdabase.GetInstance(localDir + "\\wallDB");
            init_gui_db();
            
            
        }

    private void init_gui_db()
    {
        int myInt;

        try
        {
            if (int.TryParse(Db.GetWallMgr_table_val("RestServerPort"), out myInt))
                Con_pnel_Rest_POrt_show.Text = Db.GetWallMgr_table_val("RestServerPort");
        }
        catch(Exception e)
        {}

        try
        {
                if (int.TryParse(Db.GetWallMgr_table_val("ZeroConfWait"), out myInt))
                    ZeroConfWaitTime_txtBox.Text = Db.GetWallMgr_table_val("ZeroConfWait");
        }
        catch (Exception e)
        { }

        try
        {
            if(Db.GetWallMgr_table_val("SendToTray").ToLower() == "false")
            SendToTrary_checkBox.Checked = false;
            else
                SendToTrary_checkBox.Checked = true; 

        }
        catch(Exception e)
        {}

        try
        {
            switch (Db.GetWallMgr_table_val("ZeroConfWait"))
            {
                case "cgi":
                    Wall_UoloadMethod_Cgi_radio.Checked = true;
                    break;
                case "tftp":
                    Wall_UoloadMethod_tftp_radio.Checked = true;
                    break;
                case "scp":
                    Wall_UoloadMethod_Scp_radio.Checked = true;
                    break;
            }
        }catch(Exception e)
        {
        
        }
    
    }

        private void GlobalLedsInit()
        {
            // bool bRecoder = false;
            //  bool bAutoUpdate = true;
            Recorder_Tip.SetToolTip(Recorder_led, "Recorder");
            
            Recorder_Tip.ToolTipTitle = "off";
            isRecording = false;
        }
        private void Recorder_led_Click(object sender, EventArgs e)
        {

            if (isRecording)
            {
                Recorder_Tip.ToolTipTitle = "Off";
                Recorder_led.Blink(0);
                Recorder_led.Color = Color.Gray;
                isRecording = false;
            }
            else
            {
                Recorder_Tip.ToolTipTitle = "On";
                Recorder_led.Blink(1000);
                Recorder_led.Color = Color.Red;
                isRecording = true;
            }

        }


        private void CheckIfRestStarted()
        {
            Thread.Sleep(1000);

            if (!RestSrv.isRestRunning)
            {
                Con_pnel_Rest_POrt_show.Enabled = true;
                Rest_server_start_butt.Text = "Start";
                RestServer_group.Enabled = true;
            }
            else
                RestServer_group.Enabled = false;

        }

        private void Rest_server_stop()
        {
            RestSrv.StopRestServer();
            //Rest_server_start_butt.Enabled = true;
            Con_pnel_Rest_POrt_show.Enabled = true;
            Rest_server_start_butt.Text = "Start";
        
        }
        private void Rest_server_start_butt_Click(object sender, EventArgs e)
        {
            
            if (Rest_server_start_butt.Text == "Start")
            {
                RestSrv.StartServer(Int32.Parse(Con_pnel_Rest_POrt_show.Text), "");
                //Rest_server_start_butt.Enabled = false;
                Con_pnel_Rest_POrt_show.Enabled = false;
                Rest_server_start_butt.Text = "Stop";
            }
            else
            {
                RestSrv.StopRestServer();
                //Rest_server_start_butt.Enabled = true;
                Con_pnel_Rest_POrt_show.Enabled = true;
                Rest_server_start_butt.Text = "Start";
            
            }

            CheckIfRestStarted();

            //Rest_server_Stop_butt.Enabled = true;
        }

        

        private void WallManager_Load(object sender, EventArgs e)
        {
            if (RestSrv != null)
            Rest_server_start_butt_Click(null, null);

        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string LUserName = string.Empty;
            string Password = string.Empty;
            KP_inputBox.LoginInputBox("Login Window (user Name/Password)", ref  LUserName, ref Password);

            Login(LUserName, Password);



        }
        #region Passwords
        private static string GetAuthExpert()
        {
            char[] Data = new char[6];

            Data[0] = (char)0x67;
            Data[1] = (char)0x6C;
            Data[2] = (char)0x61;
            Data[3] = (char)0x64;
            Data[4] = (char)0x39;
            Data[5] = (char)0x39;
            //Data[6] = (char)'\0';
            string s = new string(Data);


            return s;
        }

        private static string GetkpAuth()
        {
            char[] Data = new char[9];

            Data[0] = (char)0x6B;
            Data[1] = (char)0x70;
            Data[2] = (char)0x6c;
            Data[3] = (char)0x6f;
            Data[4] = (char)0x76;
            Data[5] = (char)0x65;

            Data[6] = (char)0x79;
            Data[7] = (char)0x6f;
            Data[8] = (char)0x75;
            //Data[6] = (char)'\0';
            string s = new string(Data);


            return s;
        }

        private string GetDyki()
        {

            char[] Data = new char[11];

            Data[0] = (char)0x42;
            Data[1] = (char)0x61;
            Data[2] = (char)0x72;
            Data[3] = (char)0x63;
            Data[4] = (char)0x6F;
            Data[5] = (char)0x23;
            Data[6] = (char)0x31;
            Data[7] = (char)0x32;
            Data[8] = (char)0x38;
            Data[9] = (char)0x2F;
            Data[10] = (char)0x35;

            return new string(Data);
        }

        #endregion

        private void Login(string usr,string pass)
        {
            if (usr == "expert")
            {
                if (pass == GetAuthExpert())
                {
                    /*foreach (Button but in AdminButtons)
                    {
                        but.Enabled = true;

                    }
                    foreach (Button but in UserButtons)
                    {
                        but.Enabled = true;

                    }
                    //KortexGuiMain. // change form Caption here 
                    UserType = AdminUser_txtBox.Text;
                    groupBox47.Visible = true;
                     * */
                    Control_panel_Root_group.Enabled = true;
                    RestServer_group.Enabled = true;
                    /*UploadMethod_groupBox.Enabled = true;
                    Recorder_group.Enabled = true;
                    RestServer_group.Enabled = true;
                    Control_P_General_Group.Enabled = true;
                     * */
                }
                else
                {
                    LogOut();
                    MessageBox.Show("User Name And Password does not match");
                }
            }
            else if (pass == "user")
            {
                if (pass == "barco")
                {
                    /*foreach (Button but in UserButtons)
                    {
                        but.Enabled = true;

                    }
                     * */
                    //KortexGuiMain. // change form Caption here 
                    UserType = usr;
                }
                else
                {
                    LogOut();
                    MessageBox.Show("User Name And Password does not match");
                }

            }
            else if (usr == "kp")
            {
                if (pass == GetkpAuth())
                {
                    /*foreach (Button but in AdminButtons)
                    {
                        but.Enabled = true;

                    }
                    foreach (Button but in UserButtons)
                    {
                        but.Enabled = true;

                    }
                    //KortexGuiMain. // change form Caption here 
                    UserType = AdminUser_txtBox.Text;
                    Debuf_Encrypt_file.Visible = true;
                    Debuf_Dycrypt_file.Visible = true;
                    */
                }
                else
                {
                    LogOut();
                    MessageBox.Show("User Name And Password does not match");
                }


            }
            else
            {
                LogOut();
                MessageBox.Show("User Name And Password does not match");

            }

            //Hw_mem_test_Pass_box.Clear();
            //AdminUser_txtBox.Clear();
        
        }

        private void LogOut()
        {
            /*UploadMethod_groupBox.Enabled = false;
            Recorder_group.Enabled = false;
            RestServer_group.Enabled = false;
             * */
            Control_panel_Root_group.Enabled = false;
            RestServer_group.Enabled = false;
        
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LogOut();

        }

        private void Wall_UoloadMethod_tftp_radio_CheckedChanged(object sender, EventArgs e)
        {
            DialogResult ret = System.Windows.Forms.DialogResult.None;
            if (Wall_UoloadMethod_tftp_radio.Checked)
               ret =   MessageBox.Show("For Tftp Method you must run tftp Server and put the File at tftp root and File name must be RawSpi.bin. Do you Like to start a inbuit tftp Server ?.", "WARNING!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ret == System.Windows.Forms.DialogResult.Yes)
            {
                string cmd = string.Empty;
                string exe = string.Empty;
                

                exe = localDir + "\\tftpsrv.exe";
                cmd = "";

                System.Diagnostics.ProcessStartInfo Input = new ProcessStartInfo(@exe, cmd);
                //Input.CreateNoWindow = true;
                //Input.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                System.Diagnostics.Process kp = System.Diagnostics.Process.Start(Input);


                MessageBox.Show("Your TFTP root is "+ localDir);
 
            
            }

        }

        private void Thread_optimization_check_CheckedChanged(object sender, EventArgs e)
        {
            DialogResult ret = MessageBox.Show("This Action Will Disconnect all Cubes and Destroy All reader and worker thread and create again Do you wish to continue?","WARNING!!",  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ret != System.Windows.Forms.DialogResult.Yes) return;
            

                
            if (Thread_optimization_check.Checked)
                {
                    if (!isRespWorkerRunning)
                    {
                        Wall_mnuDisConnect_Click(null, null);
                        isRespWorkerRunning = true;
                        Rev_responce_worker = new Thread(proc_recv_responceT);
                        Rev_responce_worker.Name = "Wall Resp Worker";
                        Rev_responce_worker.Start();
                        Thread.Sleep(1000);
                        Wall_mnuConnect_Click(null, null);
                    }
                }
                else
                {
                    isRespWorkerRunning = false;
                    Rev_responce_worker.Abort();
                    Wall_mnuDisConnect_Click(null, null);
                    Thread.Sleep(1000);
                    Wall_mnuConnect_Click(null, null);
                }
            

        }

        private void autoAssignToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }


        private byte[] ReadFileIps(string file)
        {
            FileStream inStream = null;
            try
            {
                inStream = File.OpenRead(file);
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show("File not found");
                return null;
            }
            catch (FileLoadException)
            {
                MessageBox.Show("File Load Exception");

                return null;
            }
            catch (DirectoryNotFoundException)
            {

                MessageBox.Show("Directory Not found");
                return null;

            }
            catch (FieldAccessException)
            {

                MessageBox.Show("FieldAccessException");
                return null;

            }
            catch (IOException er)
            {
                MessageBox.Show(er.Message);

                return null;

            }
            int count = 0;
            byte[] Buff = new Byte[inStream.Length];
            count = inStream.Read(Buff, 0, (Int32)inStream.Length);
            inStream.Close();
            //string sJSON = System.Text.ASCIIEncoding.ASCII.GetString(Buff);

            return Buff;
        
        }

        private void RemoveDuplicate_and_white_space()
        {
            LoadedIps.Sort();
            Int32 index = 0;
            while (index < LoadedIps.Count - 1)
            {
                /*if (LoadedIps[index] == string.Empty || LoadedIps[index].Length < 2)
                {
                    LoadedIps.RemoveAt(index);
                    index++;
                }
                 * */
                
                
                if (LoadedIps[index] == LoadedIps[index + 1])
                    LoadedIps.RemoveAt(index);
                else
                    index++;

                
            }
        
        }

        private string GetSerial(string Inputdata)
        {
            int startIndex,endindex;
            string Serial = string.Empty;

            startIndex = Inputdata.LastIndexOf("[");
            endindex = Inputdata.LastIndexOf("]");
            
            if (startIndex > 0 && endindex > 0)
            {
                Serial = Inputdata.Substring((startIndex + 1), ((endindex - startIndex)-1));
            }

            return Serial;
        
        }

        private void init_IpVsSerialList()
        {
            string[] Data;
            string Ip;
            string restSerial;
            string RealSerial;
            
            
            
            Monitor.Enter(SerailVsIpMap);
            
            
            SerailVsIpMap.Clear();

            for (int i = 0; i < LoadedIps.Count; i++)
            {
                Data = LoadedIps[i].Split('|');
                if (Data.Length>1)
                {
                    Ip = Data[0];
                    restSerial = Data[1];
                    RealSerial = GetSerial(restSerial);
                    SerailVsIpMap[RealSerial] = Ip;
                }
            }
            Monitor.Exit(SerailVsIpMap);
        
        }

        private void LoadIpsFromFileToListBox(string FileName)
        {
            byte[] ips;
            ips = ReadFileIps(FileName);
            if (ips == null) return;
            string AllIps = System.Text.ASCIIEncoding.ASCII.GetString(ips);
            string[] SplitedIps = AllIps.Split('\n');

            LoadedIps.Clear();
            Selective_ip_list.Items.Clear();

            

            for (int i = 0; i < SplitedIps.Length; i++)
                LoadedIps.Add(SplitedIps[i]);

            RemoveDuplicate_and_white_space();

            init_IpVsSerialList();

            /*for (int i = 0; i < SerailVsIpMap.Count; i++)
            {
                if(ZeroConf_Show_Serial_radio.Checked)
                    Selective_ip_list.Items.Add(SerailVsIpMap.);
            }
             * */

            bSerialWise = ZeroConf_Show_Serial_radio.Checked;
            foreach (KeyValuePair<string, string> item in SerailVsIpMap)
            {
                 if(ZeroConf_Show_Serial_radio.Checked)
                     Selective_ip_list.Items.Add(item.Key + "---->" + item.Value);
                else
                     Selective_ip_list.Items.Add(item.Value);
            }

            

            //MessageBox.Show(LoadedIps[i]);
        
        }

        private void selectiveAssignToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult ret =  openFileDialog1.ShowDialog();

            if (ret != System.Windows.Forms.DialogResult.OK) return;

            LoadIpsFromFileToListBox(openFileDialog1.FileName);

        }

        private void listBox_mnu_aissgn_Click(object sender, EventArgs e)
        {

            int index = Selective_ip_list.SelectedIndex;
            string ip = Selective_ip_list.Items[index].ToString();
            ip = ip.Trim();
            TryAssignIp(ip);

        }


        private void listBox_mnu_DIrectaissgn_Click(object sender, EventArgs e)
        {

            int index = Selective_ip_list.SelectedIndex;
            string ip = Selective_ip_list.Items[index].ToString();
            ip = ip.Trim();

            ToBeAssignIp = ip;
            MessageBox.Show("Please click the Cube position to Assign " + ToBeAssignIp + "At Wall Overview Area");

        }


        private void listBox_mnu_Assign_toSelected_Click(object sender, EventArgs e)
        {

            int index = Selective_ip_list.SelectedIndex;
            string ip = Selective_ip_list.Items[index].ToString();
            ip = ip.Trim();
            AssignClickedIp(ip);

        }
        private void listBox_mnu_Delete_from_list_Click(object sender, EventArgs e)
        {

            int index = Selective_ip_list.SelectedIndex;
            Selective_ip_list.Items.RemoveAt(index);

        }

        private void TryAssignIp(string ip)
        {
            int id;

            
            
            AssinTryCube.set_ip(ip);
            AssinTryCube.Connect();

            
            if (AssinTryCube.isConnected)
            {
                id = identMgr.getNextIdent();
                ToBeAssignIp = ip;
                

                Cube_command_reqObj req = new Cube_command_reqObj(cmd_requster.wallmanagerself, id, 0, 0, commandType.cmd_cube_Blink_identify_assign_mode, null, null, null);
                AssinTryCube.Request(req);
            }
        
        }

        private void loadIpsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void AllAssignThread()
        {
            ToBeAssignIp = string.Empty;
            DialogResult ret;

            for (int i = 0; i < Selective_ip_list.Items.Count; i++)
            {
                ret = MessageBox.Show("Do you Wish to Try ?" + Selective_ip_list.Items[i].ToString(), Selective_ip_list.Items[i].ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (ret == System.Windows.Forms.DialogResult.Yes)
                {
                    ToBeAssignIp = Selective_ip_list.Items[i].ToString();
                    TryAssignIp(ToBeAssignIp);
                    while (ToBeAssignIp != string.Empty)
                    {
                        Thread.Sleep(100);

                    }


                }


            }

            Assign_ALL_butt.Enabled = true;
        }

        /*private void AssignIpToCUbe(int col,int row,string Ip)
        {
            if (!AllReadyAssigned(Ip))
            {
                ALLCubes[col, row].set_ip(Ip);
                AllIplabels[col, row].Text = Ip;
            }
            

            ToBeAssignIp = string.Empty;
        
        }*/

        private void Assign_ALL_butt_Click(object sender, EventArgs e)
        {

            //int col=0, row=0;
            /*Assign_ALL_butt.Enabled = false;
            Thread th = new Thread(AllAssignThread);
            th.Start();
            */
            /*int index = Selective_ip_list.SelectedIndex;
            string ip = Selective_ip_list.Items[index].ToString();
            ip = ip.Trim();
            AssignClickedIp(ip);
            */

            int index = 0;
            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (index < Selective_ip_list.Items.Count)
                            AssignIpToCUbe(col, row, Selective_ip_list.Items[index++].ToString().Trim());
                }
            }

        }

        private void Assign_CheckEd_butt_Click(object sender, EventArgs e)
        {

            int index = 0;
            CheckedListBox.CheckedItemCollection CheckeItem = Selective_ip_list.CheckedItems;

            for (int col = 0; col < mCol; col++)
            {
                for (int row = 0; row < mRow; row++)
                {
                    if (index < Selective_ip_list.Items.Count)
                    {
                        if(index < CheckeItem.Count)
                            AssignIpToCUbe(col, row, CheckeItem[index++].ToString().Trim());
                        
                    }

                }
            }
        }

        private void ZeroConf_search_butt_Click(object sender, EventArgs e)
        {
            DialogResult ret = MessageBox.Show("This Action will take atleast " + ZeroConfWaitTime_txtBox.Text + " Seconds And it Depands on a Zeroconf Software to be install prior to use.Do you wish to continue ? ", "WARNING!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ret != System.Windows.Forms.DialogResult.Yes) return;


            string cmd = string.Empty;
            string exe = string.Empty;
            bool returnVal;
            if (ZeroConfWaitTime_txtBox.Text == String.Empty) ZeroConfWaitTime_txtBox.Text = "1";
            Int32 waitTime = Convert.ToInt32(ZeroConfWaitTime_txtBox.Text);
            string outputFIle = "OVD_KVD_IP.txt";
            string Ip_file = localDir + "\\" + outputFIle;

            exe = localDir + "\\OVD_KVD_Browser.exe";
            cmd = "-w  " + ZeroConfWaitTime_txtBox.Text;


            FileInfo MyFile = new FileInfo(Ip_file);
            if (MyFile.Exists)
            {
               MyFile.Delete();
               Thread.SpinWait(10000);
                //Delay(200);
            }

            System.Diagnostics.ProcessStartInfo Input = new ProcessStartInfo(@exe, cmd);
            Input.CreateNoWindow = true;
            Input.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            System.Diagnostics.Process kp = System.Diagnostics.Process.Start(Input);


            returnVal = kp.WaitForExit(waitTime*1000);

            MyFile = new FileInfo(Ip_file);
            if (!MyFile.Exists)
            {
                MessageBox.Show("Failed to Search IPs Please check if Apple's Bonjour is install and running");
                return;
                //MyFile.Delete();
                //Delay(200);
            }

            LoadIpsFromFileToListBox(Ip_file);
            /*if (returnVal) MessageBox.Show("Pass");
            else MessageBox.Show("Fail");
             * */

        }

        private void ZeroConf_reload_list_Click(object sender, EventArgs e)
        {
            string Ip_file = localDir + "\\OVD_KVD_IP.txt";
            LoadIpsFromFileToListBox(Ip_file);

            //FileShow kp = new FileShow("Diagnostics Result", localDir + "\\" + "10.64.16.210" + "_" + "210" + "_DiaGnosticsFile.txt");
           // kp.Show();

        }

        

        private void Selective_ip_list_MouseClick(object sender, MouseEventArgs e)
        {
            //bool set = Selective_ip_list.GetItemChecked(Selective_ip_list.SelectedIndex);
            //Selective_ip_list.SetItemChecked(Selective_ip_list.SelectedIndex, !set);
        }

        private void WallManager_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized && SendToTrary_checkBox.Checked)
            {

                this.Hide();
                notifyIcon1.Visible = true;
                /*notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(3000);
                this.ShowInTaskbar = false;
                 * */
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
        }

    
        private void Selective_ip_list_KeyDown(object sender, KeyEventArgs e)
        {
            string SerialNumber = string.Empty;

            if (e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control)
            {
                
                KP_inputBox.InputBox("Type Serial Number to be Searched", "Serial Number", ref  SerialNumber);
                //Selective_ip_list
                for (int i = 0; i < Selective_ip_list.Items.Count; i++)
                {
                    string SerialPip = Selective_ip_list.Items[i].ToString();
                    string[] RealSerial = SerialPip.Split("---->".ToCharArray());
                    if (RealSerial.Length > 1)
                        if (SerialNumber == RealSerial[0])
                                Selective_ip_list.SetSelected(i, true);
                }
            }
        }

        private void Con_pnel_Rest_POrt_show_Leave(object sender, EventArgs e)
        {
            Db.Set_WallMgr_table_val("RestServerPort", Con_pnel_Rest_POrt_show.Text);
            Db.Commit_wallMgr_Table();
        }

        

        private void ZeroConfWaitTime_txtBox_Leave(object sender, EventArgs e)
        {
            Db.Set_WallMgr_table_val("ZeroConfWait", ZeroConfWaitTime_txtBox.Text);
            Db.Commit_wallMgr_Table();
        }

        

        private void SendToTrary_checkBox_CheckedChanged_1(object sender, EventArgs e)
        {
            Db.Set_WallMgr_table_val("SendToTray", SendToTrary_checkBox.Checked.ToString());
            Db.Commit_wallMgr_Table();

        }

        

        
    
    }

    public class WallConfig_obj
    {
        public WallConfig_obj(int Col,int row)
        {
            mCol = Col;
            mRow = row;
        }
        public int mCol;
        public int mRow;


    }
}


/* MenuItem mnuSetIp = new MenuItem("Set ip");
            MenuItem mnu_Connect = new MenuItem("Connect");
            MenuItem mnuUpdate = new MenuItem("update");
            MenuItem mnuOpState = new MenuItem("Operation state");
           
            
            mnu_Connect.Click += new EventHandler(Cube_mnuConnect_Click);
             
           mnu.MenuItems.AddRange(new MenuItem[] { mnuSetIp, mnu_Connect, mnuUpdate, mnuOpState });
            */

/*mnuUpdate.MenuItems[0].Click += new EventHandler(Cube_mnuUpdate_spi_flash_Click);
           mnuUpdate.MenuItems[1].Click += new EventHandler(Cube_mnuUpdate_mmc_flash_Click);
           mnuUpdate.MenuItems[2].Click += new EventHandler(Cube_mnuUpdate_mstar_flash_Click);
           mnuUpdate.MenuItems[3].Click += new EventHandler(Cube_mnuUpdate_ps171_Bank2_flash_Click);
           */
//mnuOpState.MenuItems.Add(


